package com.demo.handler;

import com.alibaba.fastjson.JSON;
import com.demo.config.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/27 9:16
 * @Description: 统一 Controller 返回值格式
 */
@ControllerAdvice(basePackages = "com.demo.controller")
public class ControllerResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 支持所有的返回值类型
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof Response) {
            return o;
        }
        if (o instanceof String) {
            return JSON.toJSONString(Response.ok(o));
        }
        return Response.ok(o);
    }
}
